package com.red.wood.module.eval.mybatis.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.red.wood.common.domain.Page;
import com.red.wood.common.springjdbc.SqlServerDao;
import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.module.eval.mybatis.dao.EvalPassEnterpriseDao;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class EvalPassEnterpriseService {

	@Autowired
	private EvalPassEnterpriseDao dao;
	
	@Autowired
	private SqlServerDao sqlServerDao;
	
	public Map<String, Object> getPageData(IMap param) throws IOException {
		Page page = (Page) param.get("page");
		int offset = (page.getPageNo() - 1) * page.getPageSize();
		
		IMap map = sqlServerDao.getEnterpriseAuthority(param.getString("userId"));
		
		String input = IOUtils.toString(EvalPassEnterpriseService.class.getClassLoader().getResourceAsStream("user_parser.json"),"UTF-8");
		JSONArray jArray = JSONArray.fromObject(input);
		JSONObject jsonObject = jArray.getJSONObject(0);
		
		String loginUser = CommonUtils.valueOf(map.get("loginUser"));
		int userAuthority = map.getInt("userAuthority");
		
		String province = "";
		String operator = "";
		String enterprise = "";
		
		if(userAuthority == 4) {//增值企业
			enterprise = map.getString("realName");
		}else if(userAuthority == 5){//超级管理员
		}else {
			String value = jsonObject.getString(loginUser);
			if(userAuthority == 1) {//管局账号
				province = value;
			}else if(userAuthority == 2) {//集团账号(移动、电信、联通)
				operator = value;
			}else if(userAuthority == 3) {//省级基础电信企业(分省和运营商),如北京电信
				province = value.split("-")[0];
				operator = value.split("-")[1];
			}
		}
		int pageSize = page.getPageSize();
		param.put("userAuthority", userAuthority);
		param.put("province", province);
		param.put("operator", operator);
		param.put("enterprise",enterprise);
		param.put("pageSize", pageSize);
		param.put("offset", offset);
		
		long count = 0;
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		count = dao.getCount(param);
		list = dao.getPageData(param);
		
		Map<String, Object> rs = new HashMap<String, Object>();
		rs.put("totalCount", count);
		rs.put("pageData", list);
		return rs;
	}
	
}
